package org.jeecg.modules.basedata.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.*;
import org.jeecg.enums.base.BaseRentStatusEnum;
import org.jeecg.enums.base.BaseRoomPropertyEnum;
import org.jeecg.modules.basedata.service.*;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.vo.basedata.BaseTenantExcel;
import org.jeecg.vo.basedata.BaseTenantPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 租户
 * @Author: jeecg-boot
 * @Date:   2019-07-30
 * @Version: V1.0
 */
@Slf4j
@Api(tags="租户")
@RestController
@RequestMapping("/b/basedata/baseTenant")
public class BaseTenantController {
	@Autowired
	private IBaseTenantService baseTenantService;

	@Autowired
	private IBaseRoomService baseRoomService;

	@Autowired
	private IBaseProjectService baseProjectService;

	@Autowired
	private IBaseFloorService baseFloorService;

	@Autowired
	private IBaseTenantDetailService baseTenantDetailService;


	 /**
	  * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	  *
	  * @return
	  */
	 @AutoLog(value = "房间树查询")
	 @ApiOperation(value="房间管理-树查询", notes="房间管理-树查询")
	 @RequestMapping(value = "/queryTenantTreeList", method = RequestMethod.GET)
	 public Result<List<SysDepartTreeModel>> queryRoomTreeList(@RequestParam(name = "menuPath",required = false) String menuPath) {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 List<SysDepartTreeModel> list = baseTenantService.queryTenantTreeList(menuPath);
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }


	 /**
	  * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	  * @return
	  */
	 @AutoLog(value = "楼宇树查询")
	 @ApiOperation(value="楼宇管理-树查询", notes="楼宇管理-树查询")
	 @RequestMapping(value = "/queryFloorTreList", method = RequestMethod.GET)
	 public Result<List<SysDepartTreeModel>> queryFloorTreList(){
	 	Result<List<SysDepartTreeModel>> result = new Result<>();
	 	try {
			List<SysDepartTreeModel> list =baseTenantService.querFloorTreList();
			result.setResult(list);
			result.setSuccess(true);
		}catch (Exception e){
	 		log.error(e.getMessage(),e);
		}
	 	return  result;
	 }




	/**
	  * 分页列表查询
	 * @param baseTenant
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "租户-分页列表查询")
	@ApiOperation(value="租户-分页列表查询", notes="租户-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BaseTenantPage>> queryPageList(BaseTenantPage baseTenant,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<BaseTenantPage>> result = new Result<IPage<BaseTenantPage>>();
		try{
			Page<BaseTenantPage> page = new Page<BaseTenantPage>(pageNo, pageSize);
			IPage<BaseTenantPage> pageList = baseTenantService.getBaseTenantList(page, baseTenant);
			result.setSuccess(true);
			result.setResult(pageList);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *   添加
	 * @param baseTenant
	 * @return
	 */
	@AutoLog(value = "租户-添加")
	@ApiOperation(value="租户-添加", notes="租户-添加")
	@PostMapping(value = "/add")
	public Result<BaseTenant> add(@RequestBody BaseTenant baseTenant) {
		Result<BaseTenant> result = new Result<BaseTenant>();
		try {
			BaseRoom room  = baseRoomService.getById(baseTenant.getRoomId());
			if (room == null){
				return Result.error("未查询到当前房间信息！");
			}
			baseTenant.setFloorId(room.getFloorId());
			baseTenant.setProjectId(room.getProjectId());
			baseTenantService.save(baseTenant);
			//修改租赁状态
//			room.setRentStatus(BaseRentStatusEnum.BASE_RENT_STATUS_YES.getCode());
			baseRoomService.updateById(room);
			//插入租金记录
			BaseTenantDetails detail = new BaseTenantDetails();
			BeanUtils.copyProperties(baseTenant, detail);
			detail.setBaseTenantId(baseTenant.getId());
			detail.setId(null);
			baseTenantDetailService.save(detail);

			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param baseTenant
	 * @return
	 */
	@AutoLog(value = "租户-编辑")
	@ApiOperation(value="租户-编辑", notes="租户-编辑")
	@PutMapping(value = "/edit")
	public Result<BaseTenant> edit(@RequestBody BaseTenant baseTenant) {
		Result<BaseTenant> result = new Result<BaseTenant>();
		BaseTenant baseTenantEntity = baseTenantService.getById(baseTenant.getId());
		if(baseTenantEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = baseTenantService.updateById(baseTenant);
			//插入租金记录
			BaseTenantDetails detail = new BaseTenantDetails();
			BeanUtils.copyProperties(baseTenant, detail);
			detail.setBaseTenantId(baseTenant.getId());
			detail.setId(null);
			baseTenantDetailService.save(detail);

			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "租户-通过id删除")
	@ApiOperation(value="租户-通过id删除", notes="租户-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			BaseTenant tenant  = baseTenantService.getById(id);
			if (tenant == null){
				return Result.error("未查询到当前租赁信息!");
			}
			BaseRoom room = baseRoomService.getById(tenant.getRoomId());
			if (room == null){
				return Result.error("未查询到当前房间信息!");
			}
			//修改房间租赁状态
//			room.setRentStatus(BaseRentStatusEnum.BASE_RENT_STATUS_NO.getCode());
			baseRoomService.updateById(room);
			baseTenantService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "租户-批量删除")
	@ApiOperation(value="租户-批量删除", notes="租户-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<BaseTenant> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<BaseTenant> result = new Result<BaseTenant>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.baseTenantService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "租户-通过id查询")
	@ApiOperation(value="租户-通过id查询", notes="租户-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BaseTenant> queryById(@RequestParam(name="id",required=true) String id) {
		Result<BaseTenant> result = new Result<BaseTenant>();
		BaseTenant baseTenant = baseTenantService.getById(id);
		BaseRoom baseRoom = baseRoomService.getById(baseTenant.getRoomId());
		baseTenant.setFloorId(baseRoom.getFloorId());
		if(baseTenant==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(baseTenant);
			result.setSuccess(true);
		}
		return result;
	}

	@GetMapping(value = "/detailById")
	public Result<BaseTenant> detailById(@RequestParam(name="id",required=true) String id,
										 @RequestParam(name="methodId",required=true) String methodId) {
		Result<BaseTenant> result = new Result<BaseTenant>();
		BaseTenant baseTenant = baseTenantService.detailById(id, methodId);
		if(baseTenant==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(baseTenant);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, BaseTenantPage baseTenant) {
	  LoginUser user = SsoUtil.getLoginUser();
      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
	  Page<BaseTenantPage> page = new Page<BaseTenantPage>(1, Integer.MAX_VALUE);
	  IPage<BaseTenantPage> pageList = null;
	  if(StringUtils.isNotEmpty(baseTenant.getFloorId())){
		  pageList = baseTenantService.getBaseTenantList(page, baseTenant);
	  }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "租户列表");
      mv.addObject(NormalExcelConstants.CLASS, BaseTenantPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("租户列表数据", "导出人:" + user.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList.getRecords());
      return mv;
  }

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			int titleRow = 0;
			params.setTitleRows(titleRow);
			params.setHeadRows(titleRow);
			params.setNeedSave(true);
			try {
				List<BaseTenantExcel> baseTenantExcelList = ExcelImportUtil.importExcel(file.getInputStream(), BaseTenantExcel.class, params);
				if(baseTenantExcelList.size() <= 0){
					return Result.error("文件内容为空，导入失败!");
				}
				//禁止同一房间一次性做多种操作
				Set<String> setPrimary = new HashSet<>();
				for (BaseTenantExcel excel : baseTenantExcelList){
					setPrimary.add(excel.getFloorName()+excel.getRoomName());
				}
				if (setPrimary.size() != baseTenantExcelList.size()){
					return Result.error("同一楼宇同一房间不允许一次性导入多条数据，导入失败！");
				}
				int failureNum = 0;
				StringBuilder failureMsg = new StringBuilder();
				//租户信息
				List<BaseTenant> baseTenants = new ArrayList<>();
				//房间信息
				List<BaseRoom> baseRoomList = new ArrayList<>();
				for (BaseTenantExcel baseTenantExcel: baseTenantExcelList){
					titleRow++;
					if (StringUtils.isBlank(baseTenantExcel.getProjectName())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入项目名称; ");
						failureNum++;
						continue;
					}
					BaseProject baseProject = baseProjectService.getProjectByName(baseTenantExcel.getProjectName());
					if (baseProject == null) {
						failureMsg.append("<br/>第").append(titleRow).append("行：填写的项目名称系统中不存在; ");
						failureNum++;
						continue;
					}
					if (StringUtils.isBlank(baseTenantExcel.getFloorName())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入楼宇名称; ");
						failureNum++;
						continue;
					}
					BaseFloor baseFloor = baseFloorService.queryFloorName(baseProject.getId(), baseTenantExcel.getFloorName());
					if (baseFloor == null){
						failureMsg.append("<br/>第").append(titleRow).append("行：填写的楼宇名称系统中不存在; ");
						failureNum++;
						continue;
					}
					if (StringUtils.isBlank(baseTenantExcel.getRoomName())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入房间名称; ");
						failureNum++;
						continue;
					}
					while (baseTenantExcel.getRoomName().endsWith(".0")){
						baseTenantExcel.setRoomName(baseTenantExcel.getRoomName().substring(0,baseTenantExcel.getRoomName().length() - 2 ));
					}
					BaseRoom br = baseRoomService.getBaseRoomByName(baseTenantExcel.getRoomName(), baseFloor.getId());
					if (br == null){
						failureMsg.append("<br/>第").append(titleRow).append("行：填写的房间名称系统中不存在; ");
						failureNum++;
						continue;
					}
					if (BaseRoomPropertyEnum.BASE_ROOM_PROPERTY_BUSINESS.getCode() != br.getRoomProperty()){
						failureMsg.append("<br/>第").append(titleRow).append("行：房间["+ baseTenantExcel.getRoomName() +"]非商业产权房，无法办理租赁" );
						failureNum++;
						continue;
					}
//					if (BaseRentStatusEnum.BASE_RENT_STATUS_YES.getCode() == br.getRentStatus()){
//						failureMsg.append("<br/>第").append(titleRow).append("行：房间["+ baseTenantExcel.getRoomName() +"]已经办理出租，请勿重复操作" );
//						failureNum++;
//						continue;
//					}
					if (StringUtils.isBlank(baseTenantExcel.getName())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入租户姓名; ");
						failureNum++;
						continue;
					}
					if (StringUtils.isNotBlank(baseTenantExcel.getMobile())){
						while (baseTenantExcel.getMobile().endsWith(".0")){
							baseTenantExcel.setMobile(baseTenantExcel.getMobile().substring(0, baseTenantExcel.getMobile().length() - 2));
						}
					}
					/*if (baseTenantExcel.getStartDate() == null){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入合同开始日期; ");
						failureNum++;
						continue;
					}
					if (baseTenantExcel.getEndDate() == null){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入合同结束日期; ");
						failureNum++;
						continue;
					}*/
					if (StringUtils.isBlank(baseTenantExcel.getLicence())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入合同编号; ");
						failureNum++;
						continue;
					}
					while (baseTenantExcel.getLicence().endsWith(".0")){
						baseTenantExcel.setLicence(baseTenantExcel.getLicence().substring(0, baseTenantExcel.getLicence().length() - 2));
					}
					if (StringUtils.isBlank(baseTenantExcel.getIdcard())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入证件号码; ");
						failureNum++;
						continue;
					}

					while (baseTenantExcel.getIdcard().endsWith(".0")){
						baseTenantExcel.setIdcard(baseTenantExcel.getIdcard().substring(0, baseTenantExcel.getIdcard().length() - 2));
					}
					if (StringUtils.isBlank(baseTenantExcel.getCycle())){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入账单周期; ");
						failureNum++;
						continue;
					}
					while (baseTenantExcel.getCycle().endsWith(".0")){
						baseTenantExcel.setCycle(baseTenantExcel.getCycle().substring(0, baseTenantExcel.getCycle().length() - 2));
					}
					if (baseTenantExcel.getChargeTime() == null){
						failureMsg.append("<br/>第").append(titleRow).append("行：请输入开始收费时间; ");
						failureNum++;
						continue;
					}
					baseTenantExcel.setProjectId(baseProject.getId());
					baseTenantExcel.setFloorId(baseFloor.getId());
					BaseTenant baseTenant = new BaseTenant();
					BeanUtils.copyProperties(baseTenantExcel, baseTenant);
					baseTenant.setRoomId(br.getId());
					baseTenant.setProjectId(br.getProjectId());
					baseTenant.setFloorId(br.getFloorId());
					baseTenants.add(baseTenant);
					//修改租赁状态
//					br.setRentStatus(BaseRentStatusEnum.BASE_RENT_STATUS_YES.getCode());
					baseRoomList.add(br);
				}
				if (failureNum > 0){
					return Result.error("文件导入失败:" + failureMsg.toString());
				}
				baseTenantService.addBatchTenant(baseRoomList, baseTenants);
				return Result.ok("文件导入成功！数据行数:" + baseTenants.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入失败！");
	}


	/**
	  *   获取业主与租户id
	  * @return
	  */
	 @AutoLog(value = "业主与租户查询")
	 @ApiOperation(value="业主与租户查询", notes="业主与租户查询")
	 @RequestMapping(value = "/getTenantByRoomId", method = RequestMethod.GET)
	 public Result<BaseTenant> getTenantByRoomId(@RequestParam(name="roomId",required=true) String roomId) {
		 Result<BaseTenant> result = new Result<>();
		 BaseTenant baseTenant = baseTenantService.getTenantByRoomId(roomId);
		 result.setResult(baseTenant);
		 result.setSuccess(true);

		 return result;
	 }

	 /**
	  *   获取业主与租户id
	  * @return
	  */
	 @AutoLog(value = "业主与租户查询")
	 @ApiOperation(value="业主与租户查询", notes="业主与租户查询")
	 @RequestMapping(value = "/getByRoomId", method = RequestMethod.GET)
	 public Result<String> getByRoomId(@RequestParam(name="type",required=true) String type,@RequestParam(name="roomId",required=true) String roomId) {
		 Result<String> result = new Result<>();
		 if ("1".equals(type)){ //租户
			 try {
				String tenantId = baseTenantService.getByTenantId(roomId);
				 result.setResult(tenantId);
				 result.setSuccess(true);
			 } catch (Exception e) {
				 log.error(e.getMessage(),e);
			 }
		 }
		 if ("2".equals(type)){ //业主
			 try {
				 String tenantId = baseTenantService.getByCustomerId(roomId);
				 result.setResult(tenantId);
				 result.setSuccess(true);
			 } catch (Exception e) {
				 log.error(e.getMessage(),e);
			 }
		 }


		 return result;
	 }


}
